package com.shihan.rabbitmq.advancedfeatures;

import com.shihan.rabbitmq.advancedfeatures.config.RabbitMQConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class AdvancedfeaturesApplication {

    public static void main(String[] args) {
        SpringApplication.run(AdvancedfeaturesApplication.class, args);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 为了方便做 消费端确认的测试，在程序启动时，就往队列中放一点消息
    @Bean
    public ApplicationRunner runner() {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
                // 程序启动 2 秒后，发一轮消息
                try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }

                for (int i = 0; i < 3; i++) {
                    MessageProperties messageProperties = new MessageProperties();
                    messageProperties.setDeliveryTag(i);

                    Message message = new Message(("消息：" + i).getBytes("utf-8"), messageProperties);
                    rabbitTemplate.convertAndSend(
                            RabbitMQConfig.EXCHANGE_NAME_DIRECT,
                            RabbitMQConfig.BINDING_KEY,
                            message
                    );
                }

            }
        };
    }

}
